package com.golxen.framework.netty.websocket.shaker;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

//判断哪个websocket版本，然后重写编码和解码，最后其实就是加上我们的PBPacket编码而已
public class HandshakerFactory {

	private static final InternalLogger logger = InternalLoggerFactory.getInstance(HandshakerFactory.class);

	private final String webSocketURL;

	private final String subprotocols;

	private final boolean allowExtensions;

	private final int maxFramePayloadLength;

	public HandshakerFactory(String webSocketURL, String subprotocols, boolean allowExtensions) {
		this(webSocketURL, subprotocols, allowExtensions, 65536);
	}

	public HandshakerFactory(String webSocketURL, String subprotocols, boolean allowExtensions,
			int maxFramePayloadLength) {
		this.webSocketURL = webSocketURL;
		this.subprotocols = subprotocols;
		this.allowExtensions = allowExtensions;
		this.maxFramePayloadLength = maxFramePayloadLength;
	}

	public WebSocketServerHandshaker newHandshaker(HttpRequest req) {

		String version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
		if (version == null) {
			return new Handshaker00(webSocketURL, subprotocols, maxFramePayloadLength);
		}

		if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) {
			return new Handshaker13(version, version, allowExtensions, maxFramePayloadLength);
		}
		if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) {
			return new Handshaker08(version, version, allowExtensions, maxFramePayloadLength);
		}
		if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) {
			return new Handshaker07(version, version, allowExtensions, maxFramePayloadLength);
		}

		logger.error("WebSocket handshaker not find");
		return null;
	}

}
